from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import ddddocr
import cv2
import random
from PIL import Image

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=C:/Users/20486/AppData/Local/Google/Chrome/User Data/Default")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get("https://www.smzdm.com/")
time.sleep(5)

driver.find_element("xpath",
                    "//div[@class='nav-controls']/span[@class='nav-logins']/a[@class='J_login_trigger']").click()
time.sleep(5)
# 切换iframe容器标签嵌套的网站窗口
driver.switch_to.frame(driver.find_element("xpath", "//iframe[@id='J_login_iframe']"))
driver.find_element("xpath", "//div[@class='qrcode-change J_qrcode_change']").click()
time.sleep(1)
driver.find_element("xpath", "//input[@id='username']").send_keys("13281195578")
driver.find_element("xpath", "//input[@id='password']").send_keys("Abc123456")
driver.find_element("xpath", "//input[@id='loginAgreement']").click()
driver.find_element("xpath", "//input[@id='login_submit']").click()
time.sleep(5)
code_element = driver.find_element("xpath", "//div[@class='geetest_panel_box geetest_panelshowslide']")
code_element.screenshot("比价网验证码.png")

# 截取坑位图
driver.execute_script("document.getElementsByClassName('geetest_canvas_slice')[0].style.display='none'")
driver.find_element("xpath", "//div[@class='geetest_slicebg geetest_absolute']").screenshot("bg.png")
driver.execute_script("document.getElementsByClassName('geetest_canvas_slice')[0].style.display='block'")
# 截取纯背景图
driver.execute_script("document.getElementsByClassName('geetest_canvas_fullbg')[0].style.display='block'")
driver.find_element("xpath", "//div[@class='geetest_slicebg geetest_absolute']").screenshot("fullpage.png")
driver.execute_script("document.getElementsByClassName('geetest_canvas_fullbg')[0].style.display='none'")


# 识别距离
# slide = ddddocr.DdddOcr(det=False, ocr=False)
# with open('bg.png', 'rb') as f:
#     target_bytes = f.read()
# with open('fullpage.png', 'rb') as f:
#     background_bytes = f.read()
# img = cv2.imread("bg.png")
# res = slide.slide_comparison(target_bytes, background_bytes)
# distance = res['target'][0]
# print("滑动距离：",distance)

# 识别距离
def get_distance():
    bg_filename = 'bg.png'
    fullbg_filename = 'fullpage.png'
    bg_img = Image.open(bg_filename)
    fullbg_img = Image.open(fullbg_filename)
    # Image对象size属性：表示图片尺寸（宽，高）
    for x in range(0, bg_img.size[0]):  # 水平方向
        for y in range(bg_img.size[1]):  # 垂直方向
            pix1 = bg_img.load()[x, y]  # 按坐标获取图片的RGB值
            pix2 = fullbg_img.load()[x, y]
            # 判断像素是否差别过大
            threshold = 60
            # pix1[0] == red  pix1[1] == green   pix1[2] == blue(0~255)
            if abs(pix1[0] - pix2[0]) < threshold and abs(pix1[1] - pix2[1]) < threshold and abs(
                pix1[2] - pix2[2]) < threshold:
                pass
            else:
                return x


distance = get_distance()
print("滑动距离：", distance)


# 计算滑动轨迹
def get_track(distance):
    # 移动轨迹
    track = []
    # 当前位移
    current = 0
    # 减速阈值
    mid = distance * 0.7  # s = vt   s =  1/2 * a * t^2  s = v0t + 1/2 * a * t^2
    # 时间间隔
    t = 0.1
    # 初速度
    v = 0
    while current < distance:
        if current < mid:
            a = random.randint(5, 30)
        else:
            a = random.randint(-30, -5)
        # 初速度
        v0 = v
        # 当前速度
        v = v0 + a * t
        # 移动的位移 v0t + 1/2 at^2
        move = v0 * t + 1 / 2 * a * t * t
        # 当前的位移
        current += move
        # 加入轨迹
        track.append(round(move))

    move = distance - current
    track.append(round(move))
    return track


track = get_track(distance - 4)
print("滑动轨迹：", track)


# 模拟滑动
def move_to_gap(track):
    # 找滑块按住
    geetest_slider_button = driver.find_element("xpath", "//div[@class='geetest_slider_button']")
    ActionChains(driver).click_and_hold(geetest_slider_button).perform()
    # 滑动 模拟人的停顿
    while track:
        if len(track) == 1:
            x = track.pop() + random.randint(-3, 3)
        else:
            x = track.pop()
        if random.random() < 0.3:
            ActionChains(driver).move_by_offset(xoffset=x, yoffset=1).perform()
            time.sleep(random.random())
        else:
            ActionChains(driver).move_by_offset(xoffset=x, yoffset=1).perform()
    # 鼠标抬起 释放滑块
    ActionChains(driver).release(geetest_slider_button).perform()


move_to_gap(track)
